package egovframework.npqs.pqi.mobile.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.FruitPackingItem;
import egovframework.npqs.pqi.mobile.jsoncontent.SaveFruitItems;
import egovframework.npqs.pqi.mobile.jsonparser.FruitPackingThread;
import egovframework.npqs.pqi.mobile.jsonparser.FruitPackingThread.FruitPackingThreadCallback;
import egovframework.npqs.pqi.mobile.jsonparser.FruitPackingUpdateThread;
import egovframework.npqs.pqi.mobile.jsonparser.FruitPackingUpdateThread.FruitPackingUpdateThreadCallBack;

//선과장
public class FruitPackingActivity extends Activity implements FruitPackingThreadCallback, OnClickListener, FruitPackingUpdateThreadCallBack{
	private String resOffCd, resNo, recSeq, success;
	private AppStatus myapp;
	private Context context;
	private ProgressDialog dialog;
	private TextView titleTxt, navigation, content_1_1, content_1_2, content_2_1, content_3_1;
	private TextView content_3_2;
	private EditText edit_5_1, edit_6_1;
	private ListView listView;
	private ImageButton search_btn, btn_add, btn_miner, btn_exit, btnHome;
	private LinearLayout itemLayout;
	private Bundle extra;
	private Button footer01Btn, footer02Btn;
	private Intent intent;
	private int cnt; //동적으로 생성되는 컴포넌트들의 아이디값
	private FruitPackingThread fruitPackingThread;
	private FruitPackingUpdateThread fruitPackingUpdateThread;
	private FruitPackingItem fruitPackingItem;
	private ArrayList<SaveFruitItems> arrFruitItems;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	private final static int MSG_QUARANTINE_UPDATE_COMPLETED = 3;
	private final static int MSG_QUARANTINE_UPDATE_ERROR = 4;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("선과장");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fruit_packing);
		
		Intent intent = getIntent();
		resOffCd = intent.getStringExtra("resOffCd");
		resNo = intent.getStringExtra("resNo");
		recSeq = intent.getStringExtra("recSeq");
		
		Log.i("resOffCd", "resOffCd : "+resOffCd);
		Log.i("resNo", "resNo : "+resNo);
		Log.i("recSeq", "recSeq : "+recSeq);
		
		init();
		
	}
	
	private void init(){
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("선과장");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		cnt =0;
		
		context = getApplicationContext();
		myapp = (AppStatus) context.getApplicationContext();
		listView = (ListView)findViewById(R.id.qua_detail_list);
		
		content_1_1 = (TextView)findViewById(R.id.content_1_1);
		content_1_2 = (TextView)findViewById(R.id.content_1_2);
		content_2_1 = (TextView)findViewById(R.id.content_2_1);
		content_3_1 = (TextView)findViewById(R.id.content_3_1);
		content_3_2 = (TextView)findViewById(R.id.content_3_2);
		footer01Btn = (Button)findViewById(R.id.footer01Btn);
		footer02Btn = (Button)findViewById(R.id.footer02Btn);
		edit_5_1 = (EditText)findViewById(R.id.edit_5_1);
		edit_6_1 = (EditText)findViewById(R.id.edit_6_1);
		search_btn = (ImageButton)findViewById(R.id.search_btn);
		btn_add = (ImageButton)findViewById(R.id.btn_add);
		itemLayout = (LinearLayout) this.findViewById(R.id.add_layout);
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		//OnClickListener
		footer01Btn.setOnClickListener(this);
		footer02Btn.setOnClickListener(this);
		search_btn.setOnClickListener(this);
		
		/*search_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchDate();
			}
		});*/
		//동적으로 생성되는 레이아웃
		btn_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				itemLayout.setOrientation(LinearLayout.VERTICAL);
				//layout01
				final RelativeLayout item1 = new RelativeLayout(FruitPackingActivity.this);
				item1.setId(++cnt);
				System.out.println(cnt);
				item1.setBackgroundResource(R.drawable.list_bg);
				RelativeLayout.LayoutParams layout_param1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				item1.setLayoutParams(layout_param1);
				
				EditText areaCd = new EditText(FruitPackingActivity.this);
				areaCd.setId(++cnt);
				System.out.println(cnt);
				RelativeLayout.LayoutParams areaCdParam = new RelativeLayout.LayoutParams(200, LayoutParams.WRAP_CONTENT );
				areaCdParam.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				areaCdParam.addRule(RelativeLayout.CENTER_VERTICAL);
				areaCdParam.setMargins(0, 0, 20, 0);
				areaCd.setLayoutParams(areaCdParam);
				item1.addView(areaCd);
				
				EditText addr = new EditText(FruitPackingActivity.this);
				addr.setId(++cnt);
				System.out.println(cnt);
				RelativeLayout.LayoutParams addrParam = new RelativeLayout.LayoutParams(700, LayoutParams.WRAP_CONTENT );
				addrParam.addRule(RelativeLayout.RIGHT_OF, areaCd.getId());
				addrParam.addRule(RelativeLayout.CENTER_VERTICAL);
				addrParam.setMargins(20, 0, 20, 0);
				addr.setLayoutParams(addrParam);
				item1.addView(addr);
				
				Button minerBtn = new Button(FruitPackingActivity.this);
				minerBtn.setId(++cnt);
				System.out.println(cnt);
				RelativeLayout.LayoutParams minerBtnParam = new RelativeLayout.LayoutParams(80 , 80);
				minerBtnParam.addRule(RelativeLayout.RIGHT_OF, addr.getId());
				minerBtnParam.addRule(RelativeLayout.CENTER_VERTICAL);
				minerBtnParam.setMargins(20, 0, 20, 0);
				minerBtn.setBackgroundResource(R.drawable.del);
				minerBtn.setLayoutParams(minerBtnParam);
				item1.addView(minerBtn);
				
				//layout02
				final RelativeLayout item2 = new RelativeLayout(FruitPackingActivity.this);
				item2.setId(++cnt);
				System.out.println(cnt);
				item2.setBackgroundResource(R.drawable.list_bg);
				RelativeLayout.LayoutParams layout_param2 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				item2.setLayoutParams(layout_param2);
				
				TextView text01 = new TextView(FruitPackingActivity.this);
				text01.setId(++cnt);
				System.out.println(cnt);
				text01.setTextSize(14);
				RelativeLayout.LayoutParams text01_param = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				text01_param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				text01_param.addRule(RelativeLayout.CENTER_VERTICAL);
				text01_param.setMargins(20, 0, 0, 0);
				text01.setLayoutParams(text01_param);
				text01.setPaintFlags(text01.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG);  
				text01.setText("지정년도");
				item2.addView(text01);
				
				TextView text02 = new TextView(FruitPackingActivity.this);
				text02.setId(++cnt);
				System.out.println(cnt);
				text02.setTextSize(14);
				RelativeLayout.LayoutParams text02_param = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				text02_param.addRule(RelativeLayout.RIGHT_OF, text01.getId());
				text02_param.addRule(RelativeLayout.CENTER_VERTICAL);
				text02_param.setMargins(10, 0, 0, 0);
				text02.setLayoutParams(text02_param);
				text02.setPaintFlags(text02.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG);  
				item2.addView(text02);
				
				EditText edit01 = new EditText(FruitPackingActivity.this);
				edit01.setId(++cnt);
				System.out.println(cnt);
				RelativeLayout.LayoutParams edit01_param = new RelativeLayout.LayoutParams(300, LayoutParams.WRAP_CONTENT );
				edit01_param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
				edit01_param.addRule(RelativeLayout.CENTER_VERTICAL);
				edit01_param.setMargins(0, 0, 20, 0);
				edit01.setLayoutParams(edit01_param);
				item2.addView(edit01);
				
				TextView text03 = new TextView(FruitPackingActivity.this);
				text03.setId(++cnt);
				System.out.println(cnt);
				text03.setTextSize(14);
				RelativeLayout.LayoutParams text03_param = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				text03_param.addRule(RelativeLayout.LEFT_OF, edit01.getId());
				text03_param.addRule(RelativeLayout.CENTER_VERTICAL);
				text03_param.setMargins(100, 0, 20, 0);
				text03.setLayoutParams(text03_param);
				text03.setPaintFlags(text02.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG);  
				text03.setText("수량");
				item2.addView(text03);
				
				//레이아웃들의 텍스트 싸이즈
				areaCd.setTextSize(10);
				addr.setTextSize(10);
				text02.setTextSize(10);
				edit01.setTextSize(10);
				
				minerBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						itemLayout.removeView(findViewById(item1.getId()));
						itemLayout.removeView(findViewById(item2.getId()));
						cnt = cnt - 9 ; 
					}
				});
				
				itemLayout.addView(item1);
				itemLayout.addView(item2);
			}
		});
		
		btn_add.performClick();
		
		dateLoad();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.footer01Btn:
				resultSave();
			break;
			
		case R.id.footer02Btn:
				allRemove();
			break;
			
		case R.id.search_btn:
			if(cnt==0){
				myapp.utilm.ShowDialog(FruitPackingActivity.this, "실패", " \"+\" 버튼을 눌러 저장할 공간을 생성 해주세요.", 20);
			}else{
				searchDate();
			}
			break;

		default:
			break;
		}
		
	}
	
	/*//저장버튼
	public void resultSave(){
		//JSONObject resultData = new JSONObject();
		JSONObject obj = new JSONObject();
		JSONArray resultData = new JSONArray();
		int totalLayout = cnt/9;
		
		for(int i=1; i<=totalLayout; i++){
			try{
				obj.put("resOffCd", fruitPackingItem.getData().get(0).getFullResNo());
				obj.put("resNo", fruitPackingItem.getData().get(0).getFullResNo());
				obj.put("resSeq", "001");
				obj.put("exportAreaCd", ((EditText)findViewById(2+((i-1)*9))).getText().toString());
				obj.put("appointYear", ((TextView)findViewById(7+((i-1)*9))).getText().toString());
				obj.put("appointQty", ((EditText)findViewById(8+((i-1)*9))).getText().toString());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				resultData.put(obj);
			}catch(JSONException e){
				e.printStackTrace();
			}
		}
		showDialogNo();
		
		fruitPackingUpdateThread = new FruitPackingUpdateThread(context, this, resultData.toString());
		fruitPackingUpdateThread.start();
	}*/
	//저장버튼
	public void resultSave(){
		JSONObject resultData = new JSONObject();
		JSONObject obj = new JSONObject();
		JSONArray totalData = new JSONArray();
		int totalLayout = cnt/9;
		
		for(int i=1; i<=totalLayout; i++){
			try{
				obj.put("resOffCd",resOffCd);
				obj.put("resNo", resNo);
				obj.put("resSeq", recSeq);
				obj.put("exportAreaCd", ((EditText)findViewById(2+((i-1)*9))).getText().toString());
				obj.put("appointYear", ((TextView)findViewById(7+((i-1)*9))).getText().toString());
				obj.put("appointQty", ((EditText)findViewById(8+((i-1)*9))).getText().toString());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				totalData.put(obj);
			}catch(JSONException e){
				e.printStackTrace();
			}
		}
		try {
			resultData.put("resultData", totalData);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showDialogNo();
		
		fruitPackingUpdateThread = new FruitPackingUpdateThread(context, this, resultData.toString());
		fruitPackingUpdateThread.start();
	}
	
	//모두삭제버튼
	public void allRemove(){
		for(int i=1 ; i<=cnt; i++){
			itemLayout.removeView(findViewById(i));
		}
		cnt=0;
	}
	
	private void dateLoad(){
		fruitPackingThread = new FruitPackingThread(context, this, resOffCd, resNo, recSeq);
		fruitPackingThread.start();
		
		showDialogNo();
	}
	
	//조회버튼을 누르면 데이터를 찾아와 리스트 컴포넌트에 넣어준다.
	public void searchDate(){
		intent = new Intent(FruitPackingActivity.this, ExportFruitSearchActivity.class);
		intent.putExtra("search", edit_5_1.getText().toString());
		Log.i("search", edit_5_1.getText().toString());
		startActivityForResult(intent, 1);
	}
	
	private void layoutSetting(){
		content_1_1.setText(fruitPackingItem.getData().get(0).getFullRecNo());
		content_1_2.setText(fruitPackingItem.getData().get(0).getFullResNo());
		content_2_1.setText(fruitPackingItem.getData().get(0).getPrdlstNm());
		content_3_1.setText(fruitPackingItem.getData().get(0).getOrgNatNm());
		content_3_2.setText(fruitPackingItem.getData().get(0).getInsQty());
		
	}
	
	private void showDialogNo() {
		dialog = new ProgressDialog(FruitPackingActivity.this);
		dialog.setMessage(context.getApplicationContext().getString(R.string.data_load));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
	}

	@Override
	public void OnFruitPackingCompleted(boolean isNetworkConntected,
			FruitPackingItem fruitPackingItem) {
		
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}else{
			this.fruitPackingItem = fruitPackingItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnFruitPackingError(ErrorItem errorItem) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		Log.i("errorItem.getrDesc()", errorItem.getrDesc());
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				myapp.utilm.ShowDialog(FruitPackingActivity.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);
				break;
				
			case MSG_QUARANTINE_UPDATE_COMPLETED:
				new AlertDialog.Builder(FruitPackingActivity.this)
				.setTitle("저장")
				.setMessage(success)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							//searchDetailAfterSave(dnsfResNo);
							//searchDetail(dnsfResNo);
							//searchDetail(offCdEdit.getText().toString()+"-"+requestNumEdit.getText().toString());
						} catch (Exception e) {

						}
					}
					
				})
				.setCancelable(false)
				.show();
				break;
				
			case MSG_QUARANTINE_UPDATE_ERROR:
				String errMsg1 = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg1 = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg1 = msg.obj.toString();	
				}
				myapp.utilm.ShowDialog(FruitPackingActivity.this, "실패", errMsg1, 20);
				break;
				
			default:
				break;
			}
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1:
			if(resultCode == 1){
				data.getStringExtra("exportAreaCd");
				data.getStringExtra("appointYear");
				data.getStringExtra("areaNm");
				data.getStringExtra("countryNm");
				data.getStringExtra("fruitNm");
				data.getStringExtra("korNm");
				data.getStringExtra("offNm");
				data.getStringExtra("zipcode");
				data.getStringExtra("lnmAdres");
				data.getStringExtra("lnmAdresDetail");
				
				EditText codeText = (EditText) findViewById(cnt-7);
				EditText addrText = (EditText) findViewById(cnt-6);
				TextView yearDate = (TextView) findViewById(cnt-2);
				EditText editText = (EditText) findViewById(cnt-1);
				
				codeText.setText(data.getStringExtra("exportAreaCd"));
				addrText.setText(data.getStringExtra("lnmAdres")+" "+data.getStringExtra("lnmAdresDetail"));
				yearDate.setText(data.getStringExtra("appointYear"));
				//editText.setText("100개");
				
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void OnFruitPackingUpdateCompleted(boolean isNetworkConntected,
			String result) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(!result.equals("")) {
			this.success = result;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_UPDATE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnFruitPackingUpdateError(ErrorItem errorItem) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_UPDATE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		Log.i("errorItem.getrDesc()", errorItem.getrDesc());
		handler.sendMessage(msg);
	};
	
	@Override
	protected void onResume() {
		if(myapp.isAbleHome()){
			finish();
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
}
